<template>
  <page-meta :page-style="`overflow:${showSharePopup ? 'hidden' : 'visible'};`"></page-meta>
  <PageContainer>
    <view class="container">
      <Tabs v-model="currentTab" background-color="#FFF" :isScrollTop="false">
        <Header title="我的供需" v-model="headerHeight" :data="currentTab" :is-box-shadow="false">
          <NavBox :nav-box-data="navBoxData"></NavBox>
          <TabNav tabBarColor="#2878FF" />
          <template v-if="tabsData?.length">
            <TabsItem
              v-for="(item, index) in tabsData"
              :key="index"
              :name="item.title"
              :value="item.id"
            >
              <RadioTagGroup
                v-if="item.id === 0"
                v-model="boInfoListParame.boStatus"
                :data="[
                  {
                    value: null,
                    label: '全部',
                  },
                  {
                    value: BoStatusEnum.Active,
                    label: '生效中',
                  },
                  {
                    value: BoStatusEnum.Reviewing,
                    label: '审核中',
                  },
                  {
                    value: BoStatusEnum.ReviewFailed,
                    label: '已驳回',
                  },

                  {
                    value: BoStatusEnum.Expired,
                    label: '已失效',
                  },
                  {
                    value: BoStatusEnum.Draft,
                    label: '草稿',
                  },
                ]"
              ></RadioTagGroup>

              <RadioTagGroup
                v-model="sendParams.applyStatus"
                v-if="currentTab === 1"
                :data="sendStatusTagList"
                @change="sendIntentRef?.refresh"
              />

              <view v-if="currentTab === 1" class="py-6 px-16">
                <view class="flex-1" style="height: 72rpx">
                  <TSearch placeholder="搜索供需标题" @confirm="searchConfirm"></TSearch>
                </view>
              </view>

              <RadioTagGroup
                v-model="questionsParams.isReply"
                v-if="currentTab === 2"
                :data="questionsStatusTag"
                @change="questionsRef?.refresh"
              />
            </TabsItem>
          </template>
        </Header>
      </Tabs>
      <MyBoList
        ref="myBoListRef"
        v-if="currentTab === 0"
        :parame="boInfoListParame"
        @manage="handleManage"
        @share="handleShare"
      />
      <SubmitIntentList v-if="currentTab === 1" :parame="sendParams" ref="sendIntentRef" />
      <QuestionsList v-if="currentTab === 2" :parame="questionsParams" ref="questionsRef" />
      <TButtonGroup
        :styles="{
          backgroundColor: '#fff',
          display: 'block',
        }"
      >
        <TButton
          text="发布供需"
          type="none"
          :customStyle="{
            backgroundColor: '#2878FF',
            color: '#FFFFFF',
          }"
          custom-class="h-44 linh-44 br-22"
          @click="handleToRelease"
        />
      </TButtonGroup>
      <OprationDrawer ref="oprationDrawerRef" @ok="refresh()"></OprationDrawer>
    </view>
  </PageContainer>
  <PerfectInfoDialog />
  <CustomShare v-model:visible="showSharePopup" :z-index="999" @register="customShareRegister" />
</template>

<script lang="ts" setup>
  /* myBusinessOpportunities 我的供需 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import Tabs from '@/components/tabs/index.vue';
  import TabsItem from '@/components/tabs/item.vue';
  import TabNav from '@/components/tabs/nav.vue';
  import { computed, reactive, ref } from 'vue';
  import RadioTagGroup, { type TagItem } from '../components/RadioTagGroup.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import OprationDrawer from './components/OprationDrawer.vue';
  import { navigateTo, onLoad } from '@/router';
  import NavBox, { type INavBox } from '../components/NavBox.vue';
  import {
    BoStatusEnum,
    IntentionStatusEnum,
    ReleaseTypeEnum,
  } from '@/enums/businessOpportunitiesEnum';
  import type {
    IBoInfoListQuery,
    IBusinessOpportunityList,
    IIntentionApplyRecordData,
    IQuestionPageListData,
  } from '@/api/businessOpportunities/type';
  import MyBoList from './components/MyBoList.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { createShareQuery, useAppShare } from '@/hooks/core/useAppShare';
  import { getSupplyDemandPosterData, getSupplyDemandWxShareData } from '../components/utils';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { addAppShareLog } from '@/api';
  import { createMiniCode } from '@/utils/dynamicConfig';
  import { onPageScroll, onShareAppMessage, onShow } from '@dcloudio/uni-app';
  import { getUserBoStatistics } from '@/api/businessOpportunities';
  import PerfectInfoDialog from '@/components/PerfectInfoDialog/index.vue';
  import { useUserStore } from '@/store/modules/user';
  import { IntentionStatusText } from '../intentionManage';
  import SubmitIntentList from './components/SubmitIntentList.vue';
  import { PublicBooleanEnum } from '@/enums/publicModuleEnum';
  import QuestionsList from './components/QuestionsList.vue';
  import TSearch from '@/components/TSearch/index.vue';

  const shareKey = ref<string | undefined>('');
  onLoad<'myBusinessOpportunities'>((op) => {
    shareKey.value = op.shareKey;
  });

  const oprationDrawerRef = ref<InstanceType<typeof OprationDrawer>>();
  const headerHeight = ref(0);

  const currentTab = ref(0);
  const tabsData = ref<
    {
      title: string;
      id: number;
    }[]
  >([
    {
      title: '我发布的供需',
      id: 0,
    },
    {
      title: '我提交的意向',
      id: 1,
    },
    {
      title: '我提交的问题',
      id: 2,
    },
  ]);

  // 发布的供需
  const boInfoListParame = reactive<IBoInfoListQuery>({
    boStatus: null,
    current: 0,
    size: 0,
  });

  const myBoListRef = ref<InstanceType<typeof MyBoList>>();

  function refresh() {
    myBoListRef.value?.refresh();
  }

  const handleManage = (v: IBusinessOpportunityList) => {
    oprationDrawerRef.value?.open(v);
  };

  // 提交的意向
  const sendStatusTagList: TagItem[] = [
    {
      value: null,
      label: '全部',
    },
    {
      value: IntentionStatusEnum.pending,
      label: IntentionStatusText[IntentionStatusEnum.pending],
    },
    {
      value: IntentionStatusEnum.success,
      label: IntentionStatusText[IntentionStatusEnum.success],
    },
    {
      value: IntentionStatusEnum.unsuitable,
      label: IntentionStatusText[IntentionStatusEnum.unsuitable],
    },
  ];

  const sendIntentRef = ref<InstanceType<typeof SubmitIntentList>>();
  const sendParams = reactive<IIntentionApplyRecordData>({
    applyStatus: sendStatusTagList[0].value,
    keyWord: '',
  });

  const searchConfirm = (keyWord: string) => {
    sendParams.keyWord = keyWord;
  };

  // 提交的问题
  const questionsRef = ref<InstanceType<typeof QuestionsList>>();
  const questionsStatusTag: TagItem[] = [
    {
      value: null,
      label: '全部',
    },
    {
      value: PublicBooleanEnum.NO,
      label: '待回复',
    },
    {
      value: PublicBooleanEnum.YES,
      label: '已回复',
    },
  ];

  const questionsParams = reactive<IQuestionPageListData>({
    isReply: questionsStatusTag[0].value,
  });

  onShow(() => {
    queryUserBoStatistics();
    refresh()
  });

  const queryUserBoStatistics = async () => {
    // const res = await getUserBoStatistics();
    // navBoxData[0].num = res.applyReceiveWaitNum || 0;
    // navBoxData[1].num = res.questionRceiveWaitNum || 0;
  };
  const navBoxData = reactive<INavBox[]>([
    {
      text: '推广记录',
      icon: '\ue6c5',
      fn: () => {
        navigateTo({
          name: 'extensionCenter',
        });
      },
      bgColor: '#FEF5ED',
      iconColor: '#F77536',
    },
    {
      text: '浏览记录',
      icon: '\ue6c3',
      fn: () => {
        navigateTo({
          name: 'myBrowseRecords',
        });
      },
      bgColor: '#EFFBF5',
      iconColor: '#28B082',
    },
    {
      text: '我的收藏',
      icon: '\ue669',
      num: 0,
      fn: () => {
        navigateTo({
          name: 'behaviorCollectList',
        });
      },
      bgColor: '#EFF2FE',
      iconColor: '#2878FF',
    },
    {
      text: '供需广场',
      icon: '\ue6d7',
      num: 0,
      fn: () => {
        navigateTo({
          name: 'supplyDemandSquare',
        });
      },
      bgColor: '#FFF0ED',
      iconColor: '#DA6726',
    },
  ]);

  const handleToRelease = async () => {
    navigateTo({
      name: 'releaseBusinessOpportunities',
      options: {
        releaseType: ReleaseTypeEnum.member,
        shareKey: shareKey.value,
        success: () => refresh(),
      },
    });
  };

  const showSharePopup = ref(false);
  const [
    customShareRegister,
    { setWxShareOptions, setShareLogId, setPosterDrawData, setButtons, setInternalLinkOptions },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      copyLink: true,
      insertOffiaccount: true,
    },
    disableds: {
      shortLink: true,
    },
  });

  const { setWxSharePath } = useAppShare();

  const shareCache = new Map<number, { codeImg: string; shareLogId: number; posterImg: string }>(
    [],
  );
  const handleShare = async (item: IBusinessOpportunityList) => {
    const shareCacheItem = shareCache.get(item.id);
    if (!shareCacheItem) {
      uni.showLoading({ title: '分享参数准备中...', mask: true });
    }

    const query = { id: item.id };
    const path = setWxSharePath({
      name: 'supplyDemandDetails',
      options: query,
    });
    setInternalLinkOptions({
      name: 'supplyDemandDetails',
      options: query,
    });

    const routeQuery = createShareQuery(query);
    await setWxShareOptions([getSupplyDemandWxShareData(item, path)]);
    let shareLogId = shareCacheItem?.shareLogId;
    let codeImg = shareCacheItem?.codeImg;
    if (!shareCache.has(item.id)) {
      const res = await addAppShareLog({
        path: 'supplyDemandDetails',
        query: JSON.stringify(routeQuery),
      });
      shareLogId = res.id;
      codeImg = await createMiniCode({ shareLogId });
      const posterData = getSupplyDemandPosterData(item, codeImg);
      const posterImgs = await setPosterDrawData([posterData]);
      shareCache.set(item.id, { codeImg, shareLogId, posterImg: posterImgs[0] });
      setButtons({
        share: true,
        poster: true,
        copyLink: true,
        insertOffiaccount: true,
      });
      uni.hideLoading();
    } else {
      setButtons({
        share: true,
        poster: !!shareCacheItem?.posterImg,
        copyLink: true,
        insertOffiaccount: true,
      });
      await setPosterDrawData([shareCacheItem?.posterImg || '']);
    }

    setShareLogId(shareLogId as number);
    showSharePopup.value = true;
  };

  onShareAppMessage(() => ({}));

  onPageScroll(() => {
  
  });

  wx.hideShareMenu({
    menus: ['shareAppMessage', 'shareTimeline'],
  });
</script>

<style lang="scss" scoped></style>
